package com.quyeying.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.quyeying.entity.TblMerchantEntity;
import com.quyeying.service.TblMerchantService;
import com.quyeying.utils.RedisUtil;
import com.quyeying.utils.SmsEnum;
import com.quyeying.utils.SmsUtil;
import com.quyeying.utils.result.R;
import com.quyeying.utils.JwtUtil;
import com.quyeying.utils.result.ResultEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LoginController
 * @Description 登录相关接口
 * @Author skx
 * @Date 2020/11/26
 */
@RestController
public class LoginController {

    @Resource
    RedisUtil redisUtil;
    @Resource
    SmsUtil smsUtil;
    @Resource
    TblMerchantService merchantService;

    private final static String prefix = "JWT_TOKEN_";
    @Value("${sms-code}")
    String smsCode;

    @PostMapping("/login")
    public R Login(@RequestBody Map<String, String> mapParam) {
        String USERNAME = "userName";
        String VERIFICATIONCODE = "verificationCode";
        if(StringUtils.isEmpty(mapParam.get(USERNAME)) || StringUtils.isEmpty(mapParam.get(VERIFICATIONCODE))) {
            return R.error(ResultEnum.MISS_PARAM);
        }
        //如果输入跳过的验证码不用验证
        if (!smsCode.equals(mapParam.get(VERIFICATIONCODE))){
            if(!smsUtil.checkSmsCode(mapParam.get(USERNAME), mapParam.get(VERIFICATIONCODE))) {
                return R.error(ResultEnum.VERIFYCODE_INVALID);
            }
        }
        QueryWrapper<TblMerchantEntity> merchantEntityQueryWrapper = new QueryWrapper<>();
        merchantEntityQueryWrapper.eq("account", mapParam.get(USERNAME));
        TblMerchantEntity merchantEntity = merchantService.getOne(merchantEntityQueryWrapper);
        if(ObjectUtils.isEmpty(merchantEntity)) {
            return R.error(ResultEnum.USER_NOT_EXIST);
        }
        //验证通过生成jwtToken返回前台
        String sign = JwtUtil.sign(mapParam.get(USERNAME));
        //把token存到redis
        redisUtil.set(prefix.concat(mapParam.get(USERNAME)), sign, 604800);
        Map<String, Object> map = new HashMap<>(1);
        map.put("token", sign);
        map.put("type", merchantEntity.getType());
        return R.success(map);
    }

    /**
     * 登出
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {

        String authorization = request.getHeader("Authorization");
        String userName = JwtUtil.getUserName(authorization);
        redisUtil.del(prefix.concat(userName));
        return R.success();
    }

    /**
     * 发送验证码
     */
    @GetMapping ("/sendSms")
    public R sendSms(String phone, Integer type) {

        String verificationCode = String.valueOf((int)((Math.random()*9+1)*1000));
        JsonNode jsonNode;
        //登录验证
        if(type==1) {
            jsonNode = smsUtil.sendSms(phone, verificationCode, SmsEnum.ALIBABA_SMS_DLYZ.getSignName(), SmsEnum.ALIBABA_SMS_DLYZ.getTemplateCode());
        }else {
            jsonNode = smsUtil.sendSms(phone, verificationCode, SmsEnum.ALIBABA_SMS_ZCYZ.getSignName(), SmsEnum.ALIBABA_SMS_ZCYZ.getTemplateCode());
        }
        if(jsonNode.get("Code").asText().equals("OK")) {
            //把验证码缓存到redis
            redisUtil.set(phone+"_SMS_CODE", verificationCode, 300L);
            return R.success();
        }
        return R.error(ResultEnum.UNKNOWN_ERROR);
    }
}
